// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------

const fly=require("flyio")
module.exports = class extends think.Controller {
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html
    return this.display();
  }
  async cloaAction() {
    // 订单在规定时间为付款自动作废执行方法
    // 禁止 URL 访问该 Action
    if (!this.isCli) {
      const error = this.controller('cmswing/error');
      return error.noAction('only invoked in cli mode！');
    }

    // 查询未付款，未作废的订单的订单
    const map = {
      pay_status: 0,
      status: 2,
      create_time: ['<', (new Date().getTime() - (Number(this.config('setup.ORDER_DELAY')) * 60000))],
      type: 0
    };
    const order = await this.model('order').where(map).field('id').select();
    if (!think.isEmpty(order)) {
      for (const v of order) {
        await this.model('order').where({id: v.id}).update({status:6, admin_remark: '规定时间未付款系统自动作废'});
        // 释放库存
        //await this.model('cmswing/order').stock(v.id, false);
      }
    }

    // think.logger.debug(new Date(), '订单作废任务执行时间');
    // this.end();
    return this.body = '';
  }
  
  //关闭保险柜房间
  async closbAction() {
	    // 订单在规定时间为付款自动作废执行方法
	    // 禁止 URL 访问该 Action
	    if (!this.isCli) {
	      const error = this.controller('cmswing/error');
	      return error.noAction('only invoked in cli mode！');
	    }
	    console.log('作废的保险柜房间处理流程 -- 开始:');
	    // 查询未处理，未作废的保险柜房间
	    const map = {
//	      status: 0,
	      status: ['IN', [0,1]],
	      create_time: ['<', (new Date().getTime() - (Number(this.config('setup.SAFEBOX_DELAY')) * 60000))]
	    };
	    console.log('查询超时未处理的保险柜房间 -- 开始 :');
	    const safebox = await this.model('safebox').where(map).field('id,uid,pid,deposit_count,catalog,password').select();
	    console.log('获取超时未处理的保险柜房间数量  --:'+safebox.length);
	    fly.config.timeout=10000;
  		fly.config.parseJson=true;
  		
	    if (!think.isEmpty(safebox)) {
	      console.log('超时未处理的保险柜房间更改为作废状态  --开始:');
	      for (const v of safebox) {
	    	//http://47.97.119.70:5166/GameSupport/dn?cmd=safeTimeout&uid=28&roomId=10000&type=1&num=100&sign=password
	    	const url='http://47.97.119.70:5166/GameSupport/dn?cmd=safeTimeout&uid='+v.uid+'&roomId='+v.password+'&type='+v.catalog+'&num='+v.deposit_count+'&sign=password';
	  		let ret = await fly.get(url);
	  		if(v.catalog=='2'){
	  			const mdres = await this.model('member').where({id:v.pid}).increment('coin_count',v.deposit_count);
	  		}
	        await this.model('safebox').where({id: v.id}).update({status:-1,admin_remark: '规定时间未处理系统自动作废'});
	      }
	      console.log('超时未处理的保险柜房间更改为作废状态  --结束:');
	    }
	    console.log('作废的保险柜房间处理流程 -- 结束:');
//	    think.logger.debug(new Date(), '房间作废任务执行时间');
	    return this.body = '';
	  }
  
  //分润计算
  async profitAction() {
	    // 禁止 URL 访问该 Action
	    if (!this.isCli) {
	      const error = this.controller('cmswing/error');
	      return error.noAction('only invoked in cli mode！');
	    }
	    console.log('分润处理流程 -- 开始!');
	    // 查询未分润记录
//	    var deadline = this.config('setup.PROFIT_DEADLINE');
	    var deadline = await this.model('setup').where({name:'PROFIT_DEADLINE'}).getField('value', true);
	    console.log('上次分润处理截至时间--:'+deadline);
	    let scorelog = this.mongoose('jb_scorelog', 'mongoose'); // use `mongoose` adapter type
	    let scorelogdata  = await scorelog.find({reffer_id: {$ne:0 },create_time:{$gt:parseInt(deadline)}}).sort({'create_time':1}).lean().exec();
	    console.log("scorelogdata---:"+JSON.stringify(scorelogdata));
	    
	    if(!think.isEmpty(scorelogdata)) {
	    	var len = scorelogdata.length;
	    	console.log("scorelogdata.length---:"+len);
	    	var newdeadline = scorelogdata[len-1].create_time;
	    	console.log("PROFIT_DEADLINE---:"+newdeadline);
	    	for (const v of scorelogdata) {
	    	  const member = await this.model('member').where({proxy_id:v.reffer_id}).find();
	    	  if(!think.isEmpty(member)&&member.is_admin!=1){
	    		  const rebate = await this.model('rebate').where({rebate_no:'con_coin',is_default:1}).find();
	    		  const zoning = JSON.parse(rebate.zoning);
	    		  if (think.isEmpty(zoning)) {
	    			  console.log('没有金币消耗分润配置，取默认值开始-----!');
	    		      if(!think.isEmpty(rebate.first_ratio)){
	    		    	  console.log(v._id+' 金币消耗分润第一级'+member.id+'开始-----!');
		        		  let fp_amount =Number(v.cost)/100 * Number(rebate.first_ratio)/100;
		        		  
		        		  const fplog = {
 			                user_id:member.id,
 			                proxy_id:member.proxy_id,
 			                type:3,
 			                amount:Number(fp_amount),
         			        amount_log:Number(fp_amount),
         			        status:0,
         			        origin_id:v._id,
 			                create_time: new Date().valueOf(),
 			                act_id:v.uid,
 			                note: `${member.proxy_id} 通过 [${v.uid}] 消耗金币一级分润,分润金额为：${fp_amount}`
 			             };
 			             await this.model('profit_log').add(fplog);
 			             console.log(v._id+' 金币消耗分润第一级'+member.id+'结束-----!');
 			       
 			             if(!think.isEmpty(rebate.second_ratio)){
		        			let sp_amount =Number(v.cost)/100 * Number(rebate.second_ratio)/100;
		        			const smember = await this.model('member').where({proxy_id:member.ia_uname}).find();
		        			if(!think.isEmpty(smember)&&smember.is_admin!=1){
		        				console.log(v._id+' 金币消耗分润第二级'+smember.id+'开始-----!');
		        				const splog = {
        			                user_id:smember.id,
        			                proxy_id:smember.proxy_id,
        			                type:3,
        			                amount: Number(sp_amount),
                			        amount_log:Number(sp_amount),
                			        status:0,
                			        origin_id:v._id,
        			                create_time: new Date().valueOf(),
        			                act_id:v.uid,
        			                note: `${smember.proxy_id} 通过 [${v.uid}] 消耗金币二级分润,分润金额为：${sp_amount}`
        			            };
        			            await this.model('profit_log').add(splog);
        			            console.log(v._id+' 金币消耗分润第二级'+smember.id+'结束-----!');
		        			}
    			            if(!think.isEmpty(rebate.three_ratio)){
    			        	    let tp_amount =Number(v.cost)/100 * Number(rebate.three_ratio)/100;
			        			const tmember = await this.model('member').where({proxy_id:smember.ia_uname}).find();
			        			if(!think.isEmpty(tmember)&&tmember.is_admin!=1){
			        				console.log(v._id+' 金币消耗分润第三级'+tmember.id+'开始-----!');
			        				const tplog = {
            			                user_id:tmember.id,
            			                proxy_id:tmember.proxy_id,
            			                type:3,
            			                amount:Number(tp_amount),
                    			        amount_log:Number(tp_amount),
                    			        status:0,
                    			        origin_id:v._id,
            			                create_time: new Date().valueOf(),
            			                act_id:v.uid,
            			                note: `${tmember.proxy_id} 通过 [${v.uid}] 消耗金币三级分润,分润金额为：${tp_amount}`
            			        };
            			        await this.model('profit_log').add(tplog);
            			        console.log(v._id+' 金币消耗分润第三级'+tmember.id+'结束-----!');
			        			}
			        		}
		        		 }
		        	}
	    		  } else {
	    			  console.log('有金币消耗分润配置，取默认值开始-----!');
	    			  let area = JSON.parse(member.area);
	    		      for (const val of zoning) {
	    		        if (in_array(area[0], JSON.parse(val.area))) {
	    		        	console.log('消耗分润配置中有地区配置!');
	    		        	if(!think.isEmpty(val.f_ratio)){
	  	    		    	  console.log(v._id+' 金币消耗分润第一级'+member.id+'开始-----!');
	  		        		  let fp_amount =Number(v.cost)/100 * Number(val.f_ratio)/100;
	  		        		  
	  		        		  const fplog = {
	   			                user_id:member.id,
	   			                proxy_id:member.proxy_id,
	   			                type:3,
	   			                amount:Number(fp_amount),
	           			        amount_log:Number(fp_amount),
	           			        status:0,
	           			        origin_id:v._id,
	   			                create_time: new Date().valueOf(),
	   			                act_id:v.uid,
	   			                note: `${member.proxy_id} 通过 [${v.uid}] 消耗金币一级分润,分润金额为：${fp_amount}`
	   			             };
	   			             await this.model('profit_log').add(fplog);
	   			             console.log(v._id+' 金币消耗分润第一级'+member.id+'结束-----!');
	   			       
	   			             if(!think.isEmpty(val.s_ratio)){
	  		        			let sp_amount =Number(v.cost)/100 * Number(val.s_ratio)/100;
	  		        			const smember = await this.model('member').where({proxy_id:member.ia_uname}).find();
	  		        			if(!think.isEmpty(smember)&&smember.is_admin!=1){
	  		        				console.log(v._id+' 金币消耗分润第二级'+smember.id+'开始-----!');
	  		        				const splog = {
	          			                user_id:smember.id,
	          			                proxy_id:smember.proxy_id,
	          			                type:3,
	          			                amount: Number(sp_amount),
	                  			        amount_log:Number(sp_amount),
	                  			        status:0,
	                  			        origin_id:v._id,
	          			                create_time: new Date().valueOf(),
	          			                act_id:v.uid,
	          			                note: `${smember.proxy_id} 通过 [${v.uid}] 消耗金币二级分润,分润金额为：${sp_amount}`
	          			            };
	          			            await this.model('profit_log').add(splog);
	          			            console.log(v._id+' 金币消耗分润第二级'+smember.id+'结束-----!');
	  		        			}
	      			            if(!think.isEmpty(val.t_ratio)){
	      			        	    let tp_amount =Number(v.cost)/100 * Number(val.t_ratio)/100;
	  			        			const tmember = await this.model('member').where({proxy_id:smember.ia_uname}).find();
	  			        			if(!think.isEmpty(tmember)&&tmember.is_admin!=1){
	  			        				console.log(v._id+' 金币消耗分润第三级'+tmember.id+'开始-----!');
	  			        				const tplog = {
	              			                user_id:tmember.id,
	              			                proxy_id:tmember.proxy_id,
	              			                type:3,
	              			                amount:Number(tp_amount),
	                      			        amount_log:Number(tp_amount),
	                      			        status:0,
	                      			        origin_id:v._id,
	              			                create_time: new Date().valueOf(),
	              			                act_id:v.uid,
	              			                note: `${tmember.proxy_id} 通过 [${v.uid}] 消耗金币三级分润,分润金额为：${tp_amount}`
	              			        };
	              			        await this.model('profit_log').add(tplog);
	              			        console.log(v._id+' 金币消耗分润第三级 '+tmember.id+'结束-----!');
	  			        			}
	  			        		}
	  		        		 }
	  		        	}
	    		        } else {
	    		        	console.log('消耗分润配置中没有地区配置!');
	    		        	if(!think.isEmpty(rebate.first_ratio)){
	  	    		    	  console.log(v._id+' 金币消耗分润第一级'+member.id+'开始-----!');
	  		        		  let fp_amount =Number(v.cost)/100 * Number(rebate.first_ratio)/100;
	  		        		  
	  		        		  const fplog = {
	   			                user_id:member.id,
	   			                proxy_id:member.proxy_id,
	   			                type:3,
	   			                amount:Number(fp_amount),
	           			        amount_log:Number(fp_amount),
	           			        status:0,
	           			        origin_id:v._id,
	   			                create_time: new Date().valueOf(),
	   			                act_id:v.uid,
	   			                note: `${member.proxy_id} 通过 [${v.uid}] 消耗金币一级分润,分润金额为：${fp_amount}`
	   			             };
	   			             await this.model('profit_log').add(fplog);
	   			             console.log(v._id+' 金币消耗分润第一级'+member.id+'结束-----!');
	   			       
	   			             if(!think.isEmpty(rebate.second_ratio)){
	  		        			let sp_amount =Number(v.cost)/100 * Number(rebate.second_ratio)/100;
	  		        			const smember = await this.model('member').where({proxy_id:member.ia_uname}).find();
	  		        			if(!think.isEmpty(smember)&&smember.is_admin!=1){
	  		        				console.log(v._id+' 金币消耗分润第二级'+smember.id+'开始-----!');
	  		        				const splog = {
	          			                user_id:smember.id,
	          			                proxy_id:smember.proxy_id,
	          			                type:3,
	          			                amount: Number(sp_amount),
	                  			        amount_log:Number(sp_amount),
	                  			        status:0,
	                  			        origin_id:v._id,
	          			                create_time: new Date().valueOf(),
	          			                act_id:v.uid,
	          			                note: `${smember.proxy_id} 通过 [${v.uid}] 消耗金币二级分润,分润金额为：${sp_amount}`
	          			            };
	          			            await this.model('profit_log').add(splog);
	          			            console.log(v._id+' 金币消耗分润第二级'+smember.id+'结束-----!');
	  		        			}
	      			            if(!think.isEmpty(rebate.three_ratio)){
	      			        	    let tp_amount =Number(v.cost)/100 * Number(rebate.three_ratio)/100;
	  			        			const tmember = await this.model('member').where({proxy_id:smember.ia_uname}).find();
	  			        			if(!think.isEmpty(tmember)&&tmember.is_admin!=1){
	  			        				console.log(v._id+' 金币消耗分润第三级'+tmember.id+'开始-----!');
	  			        				const tplog = {
	              			                user_id:tmember.id,
	              			                proxy_id:tmember.proxy_id,
	              			                type:3,
	              			                amount:Number(tp_amount),
	                      			        amount_log:Number(tp_amount),
	                      			        status:0,
	                      			        origin_id:v._id,
	              			                create_time: new Date().valueOf(),
	              			                act_id:v.uid,
	              			                note: `${tmember.proxy_id} 通过 [${v.uid}] 消耗金币三级分润,分润金额为：${tp_amount}`
	              			        };
	              			        await this.model('profit_log').add(tplog);
	              			        console.log(v._id+' 金币消耗分润第三级'+tmember.id+'结束-----!');
	  			        			}
	  			        		}
	  		        		 }
	  		        	  }
	    		        }
	    		      }
	    		    }
	    	  }
		    }//for end
	    	
	    	if (!think.isEmpty(newdeadline)) {
	    		await this.model('setup').where({name:'PROFIT_DEADLINE'}).update({value:newdeadline});
	    	}
	    }
	    
	    console.log('分润处理流程  -- 结束!');
	    return this.body = '';
	  }
};
